/**
 * 
 */
package com.dashboard.util;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 * @author Joao
 *
 */
public class ApplicationNavigationHandler extends NavigationHandler
{

    public static final String REDIRECT_PREFIX = "redirect";

    /**
     * {@inheritDoc}
     */
    @Override
    public void handleNavigation(FacesContext facesContext, String fromAction,
			String outcome) 
    {
		if (outcome == null)
		{
			return; // no navigation
		}

		ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
		String targetViewId = getTargetViewId(facesContext, outcome);

		if (isRedirect(outcome)) 
		{
			ExternalContext externalContext = facesContext.getExternalContext();
			String redirectPath = viewHandler.getActionURL(facesContext,
					targetViewId);

			try
			{
				externalContext.redirect(externalContext.encodeActionURL(redirectPath));
			} catch (IOException e) 
			{
				throw new FacesException(e.getMessage(), e);
			}
		} 
		else 
		{
			UIViewRoot viewRoot = viewHandler.createView(facesContext,
					targetViewId);
			facesContext.setViewRoot(viewRoot);
			facesContext.renderResponse();
		}
	}

    private boolean isRedirect(String outcome) 
    {
        return outcome.startsWith(REDIRECT_PREFIX);
    }

    private String getTargetViewId(FacesContext facesContext, String outcome)
    {
        String targetViewId;
        String viewSuffix = getDefaultViewSuffix(facesContext);

        if (isRedirect(outcome))
        {
            targetViewId = "/" + outcome.split(":")[1] + viewSuffix;
        } 
        else 
        {
            targetViewId = "/" + outcome + viewSuffix;
        }

        return targetViewId;
    }

    private String getDefaultViewSuffix(FacesContext facesContext)
    {
        String suffix = facesContext.getExternalContext().getInitParameter("javax.faces.DEFAULT_SUFFIX");

        return suffix != null ? suffix : ".jsp";
    }
}
